﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Collections;
using System.Threading;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Data;
using System.Windows.Forms.VisualStyles;

namespace myking
{
    public static class scriptClass
    {
        #region api申明
        [DllImport("user32.dll", EntryPoint = "GetCursorPos")]
        public static extern bool GetCursorPos(ref Point lpPoint);

        [DllImport("user32.dll", EntryPoint = "GetWindowText")]
        public static extern int GetWindowText(IntPtr hwnd, StringBuilder lpString, int cch);

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, string wParam, string lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, System.Text.StringBuilder lParam);

        [DllImport("User32.dll", EntryPoint = "PostMessage")]
        private static extern int PostMessage(IntPtr hWnd, int Msg, uint wParam, int t);

        [DllImport("user32.dll", EntryPoint = "mouse_event")]
        public static extern void mouse_event(int wMsg, int pointx, int pointy, int pointh, int lParam);

        [DllImport("user32.dll")]
        private static extern int GetWindowRect(IntPtr hwnd, out Rect lpRect);

        [DllImport("user32")]
        public static extern int GetSystemMetrics(int nIndex);

        [DllImport("user32")]
        public static extern bool IsWindow(IntPtr hWnd);

        [DllImport("user32.dll", CharSet = CharSet.Ansi)]
        public static extern int ShowWindow(IntPtr hwnd, int nShowCmd);

        [DllImport("kernel32.dll", ExactSpelling = true)]
        internal static extern IntPtr GetCurrentProcess();

        //[DllImport("user32.DLL")]
        //public static extern IntPtr FindWindowEx(
        //    IntPtr hwndParent, IntPtr hwndChildAfter,
        //    string lpszClass, string lpszWindow);

        //提升权限新添加
        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

        [DllImport("advapi32.dll", SetLastError = true)]
        internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);

        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
         ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool ExitWindowsEx(int flg, int rea);

        //读取进程内存的函数
        [DllImport("kernel32.dll ")]
        static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, out int lpBuffer, int nSize, out int lpNumberOfBytesRead);

        [DllImport("kernel32.dll")]
        static extern bool ReadProcessMemory(uint hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, ref uint lpNumberOfBytesRead);

        [DllImport("kernel32.dll")]
        static extern bool ReadProcessMemory(int hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, int nSize, ref uint lpNumberOfBytesRead);

        [DllImport("kernel32.dll ")]
        static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, byte[] lpBuffer, int nSize, out int lpNumberOfBytesRead);


        //通过GetWindowThreadProcessId读取查找窗体句柄进程的PID值
        [DllImport("user32.dll")]
        private static extern int GetWindowThreadProcessId(IntPtr id, out int pid);

        //得到目标进程句柄的函数
        [DllImport("kernel32.dll")]
        public static extern int OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);

        [DllImport("user32.dll", CharSet = CharSet.Ansi)]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);


        #region sendinput的api相关定义
        [DllImport("user32.dll")]
        public static extern UInt32 SendInput(UInt32 nInputs, Input[] pInputs, int cbSize);

        [StructLayout(LayoutKind.Sequential)]
        public struct MouseInput
        {
            public Int32 dx;
            public Int32 dy;
            public Int32 Mousedata;
            public Int32 dwFlag;
            public Int32 time;
            public IntPtr dwExtraInfo;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct tagKEYBDINPUT
        {
            Int16 wVk;
            Int16 wScan;
            Int32 dwFlags;
            Int32 time;
            IntPtr dwExtraInfo;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct tagHARDWAREINPUT
        {
            Int32 uMsg;
            Int16 wParamL;
            Int16 wParamH;
        }

        [StructLayout(LayoutKind.Explicit)]
        public struct Input
        {
            [FieldOffset(0)]
            public Int32 type;
            [FieldOffset(4)]
            public MouseInput mi;
            [FieldOffset(4)]
            public tagKEYBDINPUT ki;
            [FieldOffset(4)]
            public tagHARDWAREINPUT hi;
        }

        const int MouseEvent_Absolute = 0x8000;
        const int MouserEvent_Hwheel = 0x01000;
        const int MouseEvent_Move = 0x0001;
        const int MouseEvent_Move_noCoalesce = 0x2000;
        const int MouseEvent_LeftDown = 0x0002;
        const int MouseEvent_LeftUp = 0x0004;
        const int MouseEvent_MiddleDown = 0x0020;
        const int MouseEvent_MiddleUp = 0x0040;
        const int MouseEvent_RightDown = 0x0008;
        const int MouseEvent_RightUp = 0x0010;
        const int MouseEvent_Wheel = 0x0800;
        const int MousseEvent_XUp = 0x0100;
        const int MousseEvent_XDown = 0x0080;

        #endregion


        #endregion

        #region 常量声明
        const int MOUSEEVENTF_MOVE = 0x0001;     // 移动鼠标           (十):1
        const int MOUSEEVENTF_LEFTDOWN = 0x0002; //模仿鼠标左键按下    (十):2
        const int MOUSEEVENTF_LEFTUP = 0x0004; //模仿鼠标左键抬起    (十):4
        const int MOUSEEVENTF_RIGHTDOWN = 0x0008; //模仿鼠标右键按下    (十):8
        const int MOUSEEVENTF_RIGHTUP = 0x0010; //模仿鼠标右键抬起    (十):16
        const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;// 模仿鼠标中键按下    (十):32
        const int MOUSEEVENTF_MIDDLEUP = 0x0040;// 模仿鼠标中键抬起    (十):64
        const int MOUSEEVENTF_ABSOLUTE = 0x8000; //标示是否采取绝对坐标    (十):32768

        const int SM_CXSCREEN = 0;      //屏幕宽度
        const int SM_CYSCREEN = 1;      //屏幕高度

        const int WM_KEYDOWN = 0x100; //按键按下
        const int WM_KEYUP = 0x101; //按键抬起
        const int WM_CHAR = 0x0102;

        const int SW_HIDE = 0;
        const int SW_SHOWNORMAL = 1;
        const int SW_SHOWMINIMIZED = 2;
        const int SW_SHOWMAXIMIZED = 3;
        const int SW_SHOW = 6;

        const int WM_SETTEXT = 0xC;
        const int WM_GETTEXT = 0xD;

        internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
        internal const int TOKEN_QUERY = 0x00000008;
        internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        internal const int EWX_LOGOFF = 0x00000000;
        internal const int EWX_SHUTDOWN = 0x00000001;
        internal const int EWX_REBOOT = 0x00000002;
        internal const int EWX_FORCE = 0x00000004;
        internal const int EWX_POWEROFF = 0x00000008;
        internal const int EWX_FORCEIFHUNG = 0x00000010;

        const int PROCESS_ALL_ACCESS = 0x1F0FFF;
        const int PROCESS_VM_READ = 0x0010;
        const int PROCESS_VM_WRITE = 0x0020;

        #endregion

        #region 变量

        /// <summary>
        /// 是否使用调试模式
        /// </summary>
        public static string debug { get; set; }

        public static int reconnetTime { get; set; }

        public static string reconnetFlag { get; set; }

        public static string dmtypeFlag { get; set; }

        public static double delaytime { get; set; }

        public static string stopFlag { get; set; }

        public static string businesstypeName { get; set; }

        public static string checkresponflag { get; set; }

        /// <summary>
        /// 主窗口句柄
        /// </summary>
        public static IntPtr programhWnd { get; set; }

        public static IntPtr msgHwnd { get; set; }

        public static IntPtr checkhWnd { get; set; }

        /// <summary>
        /// 发送消息框
        /// </summary>
        public static IntPtr SendWnd { get; set; }

        /// <summary>
        /// 主窗口进程句柄
        /// </summary>
        public static IntPtr processHandle { get; set; }

        public static string titlename { get; set; }

        public static ArrayList responsemsg { get; set; }

        public static int loopflg { get; set; }

        private static CDmSoft prdm;

        public static string userid { get; set; }

        public static string passwd { get; set; }

        /// <summary>
        /// 是否体用前台标志
        /// </summary>
        public static string frontType { get; set; }

        public static int sendwindowhanlde { get; set; }

        /// <summary>
        /// 所有区块命令合集
        /// </summary>
        public static Dictionary<string, ArrayList> cmdarraylist { get; set; }

        /// <summary>
        /// 变量数组
        /// </summary>
        public static Dictionary<string, ArrayList> varArrayList { get; set; }

        /// <summary>
        /// 变量下标数组
        /// </summary>
        public static Dictionary<string, int> varNumberList { get; set; }

        /// <summary>
        /// 所有触发区块命令合集
        /// </summary>
        public static Dictionary<string, ArrayList> triggerList { get; set; }

        /// <summary>
        /// 游戏内部变量
        /// </summary>
        public static Dictionary<string, int> gamevalue { get; set; }

        /// <summary>
        /// 游戏匹配变量
        /// </summary>
        public static Dictionary<int, string> mathvalue { get; set; }


        private struct Rect
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        ///// <summary>
        ///// 当前mp
        ///// </summary>
        //public static int m { get; set; }

        ///// <summary>
        ///// 最大MP
        ///// </summary>
        //public static int M { get; set; }

        ///// <summary>
        ///// 当前hp
        ///// </summary>
        //public static int h { get; set; }

        ///// <summary>
        ///// 最大hp
        ///// </summary>
        //public static int H { get; set; }

        internal struct TokPriv1Luid
        {
            public int Count;
            public long Luid;
            public int Attr;
        }

        #endregion

        //系统延时(进程不停止)
        private static void delay(double tol)//tol=20s
        {
            DateTime orinowtime = DateTime.Now;//记录延时开始的系统当前时间
            while (orinowtime.AddSeconds(tol).CompareTo(DateTime.Now) >= 0)//延时20s
                loopflg = 0;
        }

        //系统延时(进程停止)
        private static void truedelay(double tol)//tol=20s
        {
            int waitsecond = (int)(tol * 1000);
            Thread.Sleep(waitsecond);
        }

        /// <summary>
        /// 系统延时(进程不停止) 延时判断
        /// </summary>
        private static int delay(double tol, ArrayList bc, string cmdmsg)
        {
            DateTime orinowTime = DateTime.Now;//记录延时开始的系统当前时间
            while (orinowTime.AddSeconds(tol).CompareTo(DateTime.Now) >= 0)//延时20s
            {
                ArrayList analylist = new ArrayList();
                analylist = analysisRespense(checkhWnd);

                if (analylist.Count > 0)
                {
                    foreach (string item in bc)
                    {
                        int bcstartpos = item.IndexOf(":", 0);
                        int bcendpos = 0;

                        if (bcstartpos > 0)
                        {
                            bcendpos = item.IndexOf(":", bcstartpos + 1);
                            if (bcendpos >= 0)
                            {
                                double triggerTime = 0;
                                if (bcendpos - bcstartpos > 1)
                                {
                                    triggerTime = Convert.ToDouble(item.Substring(bcstartpos + 1, bcendpos - bcstartpos - 1));
                                }
                                string loopType = item.Substring(0, bcstartpos);
                                string checkmsg = item.Substring(bcendpos + 1);

                                if (responsemsg.Count > 0)
                                {
                                    if (responsemsg[responsemsg.Count - 1].ToString() == "你发出的命令超过每秒20个, 连线自动关闭." || responsemsg[responsemsg.Count - 1].ToString() == "欢迎下次再来﹗" || responsemsg[responsemsg.Count - 1].ToString() == "游戏重新启动﹐请稍候一分钟再 login 。")
                                    {
                                        responsemsg[responsemsg.Count - 1] = "";
                                    }
                                }

                                if (checkResponse(analylist, checkmsg) == 1)
                                {
                                    truedelay(triggerTime);
                                    //调用子程序
                                    if (loopType.Length > 4)
                                    {
                                        if (loopType.Substring(0, 4) == "call")
                                        {
                                            return LoopScript(cmdarraylist[loopType.Substring(5, loopType.Length - 5)]);
                                        }
                                    }

                                    switch (loopType)
                                    {
                                        case "next"://注释
                                            return 0;
                                        case "exitloop":
                                            return 1;
                                        case "retry"://注释
                                            return SendOnceMessage(cmdmsg);
                                        default:
                                            break;
                                    }
                                }
                            }
                        }
                    }
                }
                truedelay(0.9);
            }
            return 0;
        }

        /// <summary>
        /// 发送单次命令
        /// </summary>
        /// <param name="instr"></param>
        /// <returns></returns>
        private static int SendOnceMessage(string instr)
        {
            while (stopFlag == "Y" && businesstypeName == "Y")
            {
                truedelay(1);
            }

            uint vk_f;
            char c;
            int n;
            double waittime;

            if (instr.Length == 8)
            {
                if (instr == "shutdown")
                {
                    businesstypeName = "N";
                }
            }

            while (businesstypeName != "Y")
            {
                return 0;
            }

            //退出循环
            if (instr.Length > 7)
            {
                if (instr.Substring(0, 8) == "exitloop")
                {
                    return 1;
                }
            }

            //调用子程序
            if (instr.Length > 4)
            {
                if (instr.Substring(0, 4) == "call")
                {
                    return LoopScript(cmdarraylist[instr.Substring(5, instr.Length - 5)]);
                }
            }

            //等待时间
            if (instr.Length > 4)
            {
                if (instr.Substring(0, 4) == "wait")
                {
                    waittime = Convert.ToDouble(instr.Substring(4, instr.Length - 4));
                    truedelay(waittime);
                    return 0;
                }
            }

            //跑点 run 1,1 1
            if (instr.Length > 8)
            {
                instr = replacecmdmsg(instr);
                if (instr.Substring(0, 4) == "run ")
                {
                    int start = instr.IndexOf(" ", 0);
                    int end = instr.IndexOf(",", 0);
                    int mousex = Convert.ToInt32(instr.Substring(start + 1, end - start - 1));

                    start = end;
                    end = instr.IndexOf(" ", end);
                    int mousey = Convert.ToInt32(instr.Substring(start + 1, end - start - 1));

                    int times = Convert.ToInt32(instr.Substring(end));

                    gamevalue["targetx"] = mousex;
                    gamevalue["targety"] = mousey;
                    return runpoint(times);
                }
            }

            int bcstartpos = instr.IndexOf(":", 0);
            int bcendpos = 0;

            if (bcstartpos > 0)
            {
                bcendpos = instr.IndexOf(":", bcstartpos + 1);
                if (bcendpos <= 0)
                {
                    return -1;
                }
            }

            Boolean bcflag = false;

            string triggerKey = string.Empty;

            if (bcendpos > bcstartpos + 1)
            {
                bcflag = true; //有判断标志
                triggerKey = instr.Substring(bcstartpos + 1, bcendpos - bcstartpos - 1);
            }
            string commandtmp = string.Empty;

            delaytime = 0.34;
            if (bcstartpos > 0)
            {
                delaytime = Convert.ToDouble(instr.Substring(0, bcstartpos));
            }

            commandtmp = instr.Substring(bcendpos + 1, instr.Length - bcendpos - 1);
            commandtmp = replacecmdmsg(commandtmp);

            #region 鼠标命令
            Boolean mouseflag = false;

            if (commandtmp.Length > 6)
            {
                if (commandtmp.Substring(0, 6) == "@&kill")
                {
                    mouseflag = true;
                    try
                    {
                        int start = commandtmp.IndexOf("(", 0);
                        int end = commandtmp.IndexOf(",", 0);
                        double mousex = Convert.ToDouble(commandtmp.Substring(start + 1, end - start - 1));

                        start = end;
                        end = commandtmp.IndexOf(")", 0);
                        double mousey = Convert.ToDouble(commandtmp.Substring(start + 1, end - start - 1));
                        CallDmMouseKill(programhWnd, mousex, mousey);
                    }
                    catch (Exception e)
                    {

                    }
                }
                else if (commandtmp.Substring(0, 6) == "@&move")
                {
                    mouseflag = true;
                    try
                    {
                        int start = commandtmp.IndexOf("(", 0);
                        int end = commandtmp.IndexOf(",", 0);
                        double mousex = Convert.ToDouble(commandtmp.Substring(start + 1, end - start - 1));

                        start = end;
                        end = commandtmp.IndexOf(")", 0);
                        double mousey = Convert.ToDouble(commandtmp.Substring(start + 1, end - start - 1));
                        CallDmMouseMove(programhWnd, mousex, mousey);
                    }
                    catch (Exception e)
                    {

                    }
                }
                else if (commandtmp.Substring(0, 6) == "@&lfup")
                {
                    mouseflag = true;
                    try
                    {
                        CallDmMouseLeftUp();
                    }
                    catch (Exception e)
                    {

                    }
                }
                else if (commandtmp.Substring(0, 6) == "@&lfdn")
                {
                    mouseflag = true;
                    try
                    {
                        CallDmMouseLeftDown();
                    }
                    catch (Exception e)
                    {

                    }
                }
                else if (commandtmp.Substring(0, 6) == "@&rtup")
                {
                    mouseflag = true;
                    try
                    {
                        CallDmRightUp();
                    }
                    catch (Exception e)
                    {

                    }
                }
                else if (commandtmp.Substring(0, 6) == "@&rtdn")
                {
                    mouseflag = true;
                    try
                    {
                        CallDmRightDown();
                    }
                    catch (Exception e)
                    {

                    }
                }
            }
            #endregion

            #region 替换用户名和密码@@playerid,@@playerpasswd,仅发送不回车
            int findpos = commandtmp.IndexOf("@@playerid", 0);

            if (findpos >= 0)
            {
                commandtmp = commandtmp.Replace("@@playerid", userid);

                if (dmtypeFlag != "Y")
                {
                    PostMessagestr(commandtmp);
                }
                else
                {
                    prdm.KeyPressChar(commandtmp);
                }
                truedelay(delaytime);
                return 0;

            }

            findpos = commandtmp.IndexOf("@@playerpasswd", 0);
            if (findpos >= 0)
            {
                commandtmp = commandtmp.Replace("@@playerpasswd", passwd);
            }

            #endregion

            if (checkhWnd != IntPtr.Zero)
            {
                analysisRespense(checkhWnd);
            }

            #region 调用系统dll控制前台键盘鼠标(执行命令并暂停返回)
            //if (Callkeyboard(commandtmp, delaytime) > 0)
            //{
            //    return 1;
            //}
            #endregion


            if (!mouseflag)
            {
                if (dmtypeFlag != "Y")
                {
                    if (!string.IsNullOrEmpty(commandtmp))
                    {
                        PostMessagestr(commandtmp);
                        vk_f = (uint)13;
                        PostMessageKeydown(vk_f);
                        if ("Y".Equals(debug))
                        {
                            Log.WriteLog("循环记录", commandtmp + ",等待时间" + delaytime.ToString(), "循环记录");
                        }

                    }
                }
                else
                {
                    prdm.SendString((int)programhWnd, commandtmp);
                    prdm.KeyPressChar("enter");
                    if ("Y".Equals(debug))
                    {
                        Log.WriteLog("循环记录", commandtmp + ",等待时间" + delaytime.ToString(), "循环记录");
                    }
                }
            }

            if (bcflag && checkhWnd != IntPtr.Zero)
            {
                return delay(delaytime, triggerList[triggerKey], instr);
            }
            else
            {
                truedelay(delaytime);
            }


            return 0;
        }

        /// <summary>
        /// 执行到某个点
        /// </summary>
        /// <returns></returns>
        private static int runpoint(int times)
        {
            GetGameVaue();

            if (gamevalue["x"] == 0 && gamevalue["y"] == 0)
            {
                return 0;
            }

            if (gamevalue["targetx"] == 0 && gamevalue["targety"] == 0)
            {
                return 0;
            }

            if (times < 1)
            {
                times = 1;
            }

            for (int i = 0; i < times; i++)
            {
                if ((gamevalue["x"] != gamevalue["targetx"]) || (gamevalue["y"] != gamevalue["targety"]))
                {
                    SendOnceMessage("1::run " + gamevalue["targetx"] + ", " + gamevalue["targety"]);
                    truedelay(1);
                    //使用内置获得当前坐标
                    //SendOnceMessage("0.5::look compass");
                }
                else
                {
                    return 0;
                }
            }
            return 0;
        }

        /// <summary>
        /// 调用api发送按键
        /// </summary>
        private static void PostMessageKeydown(uint vk_f)
        {


            if (SendWnd != IntPtr.Zero)
            {
                //发送到命令框
                PostMessage(SendWnd, WM_KEYDOWN, vk_f, 0);
            }
            if (SendWnd == IntPtr.Zero)
            {
                PostMessage(programhWnd, WM_KEYDOWN, vk_f, 0);
            }

        }

        /// <summary>
        /// 调用api发送 字符串
        /// </summary>
        private static void PostMessagestr(string commandtmp)
        {

            uint vk_f;
            char c;
            int n;
            for (int i = 0; i < commandtmp.Length; i++)
            {
                c = Convert.ToChar(commandtmp.Substring(i, 1));
                n = Convert.ToInt32(c);
                vk_f = (uint)n;

                if (SendWnd != IntPtr.Zero)
                {
                    //发送到命令框
                    PostMessage(SendWnd, WM_CHAR, vk_f, 0);
                }
                if (SendWnd == IntPtr.Zero)
                {
                    PostMessage(programhWnd, WM_CHAR, vk_f, 0);
                }
            }
        }

        /// <summary>
        /// 修改标题
        /// </summary>
        public static void ChangeTitle()
        {
            if (string.IsNullOrEmpty(titlename))
            {
                //
            }
            else
            {
                SendMessage(programhWnd, WM_SETTEXT, titlename, titlename);
            }
        }

        /// <summary>
        /// 发送命令
        /// </summary>
        public static void MySendMessage()
        {
            int checkconnet= 0;
            Init();
            while (businesstypeName == "Y")
            {
                LoopScript(cmdarraylist["begin"]);
                checkconnet++;
                //自动重连判断窗口是否存在
                if ("Y".Equals(reconnetFlag) && checkconnet > reconnetTime)
                {
                    checkconnet = 0;
                    //窗口消失
                    if (!IsWindow(programhWnd))
                    {
                        if (!ReBindWindowhandle())
                        {
                            //等待10秒避免死循环
                            truedelay(10);
                        }
                        Init();
                    }
                }

            }
        }

        public static void Init()
        {
            truedelay(1);
            InitGameValue();
            InitMathValue();

            #region 获取程序进程

            //由窗体句柄获得进程ID
            int calcID = 0;
            GetWindowThreadProcessId(programhWnd, out calcID);

            processHandle = (IntPtr)OpenProcess(0x1F0FFF, false, calcID);

            #endregion

            //CDmSoft dm = new CDmSoft();
            prdm = new CDmSoft();

            if ("Y".Equals(frontType))
            {
                truedelay(1);

                //前端绑定当前鼠标所在窗口
                sendwindowhanlde = prdm.GetMousePointWindow();

                programhWnd = (IntPtr)sendwindowhanlde;

                int result = prdm.BindWindow(prdm.GetMousePointWindow(), "normal", "normal", "windows", 0);
            }
            else
            {
                if (dmtypeFlag == "Y")
                {
                    int result = prdm.BindWindow((int)programhWnd, "normal", "normal", "windows", 0); //绑定窗口
                }
            }
            //int result = prdm.BindWindow((int)programhWnd, "normal", "normal", "windows", 0); //绑定窗口
            //ChangeTitle();

            //result = prdm.IsBind((int)programhWnd);

            analysisRespense(programhWnd); //先初始化获取一次信息


        }

        /// <summary>
        /// 重新绑定窗体
        /// </summary>
        /// <returns></returns>
        public static Boolean ReBindWindowhandle()
        {
            IntPtr hWndmsgParent = new IntPtr();
            programhWnd = scriptClass.getMasterhandle(out hWndmsgParent, userid);

            if (scriptClass.programhWnd == IntPtr.Zero)
            {
                return false;
            }

            hWndmsgParent = IntPtr.Zero;
            IntPtr hWndmsg = getmsghandle(out hWndmsgParent, userid);

            checkhWnd = hWndmsg;
            return true;
        }

        /// <summary>
        /// 循环获取命令内容
        /// </summary>
        private static int LoopScript(ArrayList inlist)
        {
            int looptimes = 0;
            int loopsecond = 0;
            ArrayList loopmsg = new ArrayList();
            ArrayList ifmsg = new ArrayList();
            Boolean ifResult = false;
            int ifOrLoopFlag = 0;
            int iftimes = 0;
            int sendresult = 0;

            foreach (var item in inlist)
            {
                if (businesstypeName != "Y")
                {
                    return 0;
                }
                if (item == null)
                {
                    continue;
                }
                string tmpstr = item.ToString();

                #region if判断标志
                if ((tmpstr.Length > 2) && (tmpstr.Substring(0, 2) == "if"))
                {
                    switch (ifOrLoopFlag)
                    {
                        case 0://普通状态
                            iftimes++;
                            ifOrLoopFlag = 1;
                            ifResult = checkifresult(tmpstr);
                            break;
                        case 1://if判断状态
                            iftimes++;
                            if (ifResult) //大循环通过
                            {
                                ifmsg.Add(tmpstr);
                            }
                            break;
                        case 2://循环状态
                            loopmsg.Add(tmpstr);
                            break;
                    }
                    continue;
                }
                #endregion

                #region endif判断标志
                if ((tmpstr.Length == 5) && (tmpstr.Substring(0, 5) == "endif"))
                {
                    switch (ifOrLoopFlag)
                    {
                        case 1://if判断状态
                            iftimes--;
                            if (iftimes <= 0) //if结束
                            {
                                if (ifResult) //大if通过
                                {
                                    sendresult = LoopScript(ifmsg); //执行if判断段
                                }
                                ifmsg.Clear();
                                ifOrLoopFlag = 0;
                                if (sendresult == 1)
                                {
                                    return 1;
                                }
                            }
                            else //继续判断if
                            {
                                if (ifResult) //大if通过
                                {
                                    ifmsg.Add(tmpstr);//添加至if段
                                }
                            }
                            break;
                        case 2://循环状态
                            loopmsg.Add(tmpstr);
                            break;
                    }
                    continue;
                }
                #endregion

                #region loop标志
                if ((tmpstr.Length > 4) && (tmpstr.Substring(0, 4) == "loop"))
                {
                    switch (ifOrLoopFlag)
                    {
                        case 0://普通状态
                            looptimes++;
                            ifOrLoopFlag = 2; //进入循环区块
                            loopsecond = Convert.ToInt32(tmpstr.Substring(4, tmpstr.Length - 4));
                            break;
                        case 1://if状态
                            if (ifResult) //大if通过
                            {
                                ifmsg.Add(tmpstr);
                            }
                            break;
                        case 2://循环状态
                            looptimes++;
                            loopmsg.Add(tmpstr);
                            break;
                    }
                    continue;
                }
                #endregion

                #region foreach区块
                //支持foreach开始
                if ((tmpstr.Length > 7) && (tmpstr.Substring(0, 7) == "foreach"))
                {
                    switch (ifOrLoopFlag)
                    {
                        case 0://普通状态
                            looptimes++;
                            ifOrLoopFlag = 2; //进入循环区块
                            string key = tmpstr.Substring(7, tmpstr.Length - 7).Trim();

                            foreach (string _key in varArrayList.Keys)
                            {
                                if (key == _key.ToString())
                                {
                                    loopsecond = varArrayList[key].Count;
                                    break;
                                }
                            }
                            if (loopsecond <= 0)
                            {
                                loopsecond = 1;
                            }
                            break;
                        case 1://if状态
                            if (ifResult) //大if通过
                            {
                                ifmsg.Add(tmpstr);
                            }
                            break;
                        case 2://循环状态
                            looptimes++;
                            loopmsg.Add(tmpstr);
                            break;
                    }
                    continue;
                }
                #endregion

                #region endloop区块
                if ((tmpstr.Length == 7) && (tmpstr.Substring(0, 7) == "endloop"))
                {
                    switch (ifOrLoopFlag)
                    {
                        case 1://if判断状态
                            if (ifResult) //大if通过
                            {
                                ifmsg.Add(tmpstr);
                            }
                            break;
                        case 2://循环状态
                            looptimes--;
                            if (looptimes <= 0)
                            {
                                for (int i = 0; i < loopsecond; i++)
                                {
                                    //遇到退出循环 exit
                                    if (LoopScript(loopmsg) == 1)
                                    {
                                        //loop测试1106
                                        //break;
                                        loopmsg.Clear();
                                        ifOrLoopFlag = 0;
                                        return 1;
                                    }
                                }
                                loopmsg.Clear();
                                ifOrLoopFlag = 0;
                            }
                            else
                            {
                                loopmsg.Add(tmpstr);
                            }
                            break;
                    }
                    continue;
                }
                #endregion

                #region loop区块
                //支持foreach结束
                if ((tmpstr.Length == 4) && (tmpstr == "loop"))
                {
                    switch (ifOrLoopFlag)
                    {
                        case 1://if判断状态
                            if (ifResult) //大if通过
                            {
                                ifmsg.Add(tmpstr);
                            }
                            break;
                        case 2://循环状态
                            looptimes--;
                            if (looptimes <= 0)
                            {
                                for (int i = 0; i < loopsecond; i++)
                                {
                                    //遇到退出循环 exit
                                    if (LoopScript(loopmsg) == 1)
                                    {
                                        break;
                                    }
                                }
                                loopmsg.Clear();
                                ifOrLoopFlag = 0;
                            }
                            else
                            {
                                loopmsg.Add(tmpstr);
                            }
                            break;
                    }
                    continue;
                }
                #endregion

                #region 普通代码
                switch (ifOrLoopFlag)
                {
                    case 0://普通状态
                        sendresult = SendOnceMessage(tmpstr);
                        break;
                    case 1://if判断状态
                        if (ifResult) //大循环通过
                        {
                            ifmsg.Add(tmpstr);
                        }
                        break;
                    case 2://循环状态
                        loopmsg.Add(tmpstr);
                        break;
                }
                #endregion
            }

            return sendresult;

        }

        /// <summary>
        /// 前台鼠标移动
        /// </summary>
        public static void movemouse()
        {
            int x = 0;
            int y = 0;

            // 获取当前鼠标坐标
            delay(delaytime);
            Point defpoint = new Point();
            GetCursorPos(ref defpoint);
            x = defpoint.X;
            y = defpoint.Y;

            //换算到event点
            int mx = x * 65535 / GetSystemMetrics(SM_CXSCREEN);
            int my = y * 65535 / GetSystemMetrics(SM_CYSCREEN);
            mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, mx, my, 0, 0);

            //移动鼠标,右键点击
            mouse_event(0x0008, 0, 0, 0, 0);//右键down 
            delay(0.1);//按下与松开之间需要暂停
            mouse_event(0x0010, 0, 0, 0, 0);//右键up

        }

        /// <summary>
        /// 窗口显示
        /// </summary>
        public static void setwindowShow()
        {
            ShowWindow(programhWnd, SW_SHOW);

        }

        /// <summary>
        /// 显示指定句柄
        /// </summary>
        public static void setwindowShow(IntPtr hwnd)
        {
            ShowWindow(hwnd, SW_SHOW);

        }

        /// <summary>
        /// 隐藏指定句柄
        /// </summary>
        public static void setwindowHide(IntPtr hwnd)
        {
            ShowWindow(hwnd, SW_HIDE);

        }

        /// <summary>
        /// 窗口隐藏
        /// </summary>
        public static void setwindowHide()
        {
            //SW_HIDE
            ShowWindow(programhWnd, SW_HIDE);

        }

        /// <summary>
        /// 先获取脚本中所有的key值
        /// </summary>
        private static int getCommandKey(ArrayList inlist, out ArrayList outKey, out string errormsg)
        {
            errormsg = string.Empty;
            outKey = new ArrayList();
            Boolean beginflag = false;
            Boolean keyfind = false;
            string key = string.Empty; //分类
            foreach (var item in inlist)
            {
                if (item == null)
                {
                    continue;
                }
                string commanLine = item.ToString().Trim();
                if (string.IsNullOrEmpty(commanLine))
                {
                    continue;
                }

                switch (commanLine.Substring(0, 1))
                {
                    case "#"://注释
                    case "/"://注释
                    case "-"://注释
                        continue;
                    default:
                        break;
                }

                //判断区块标志
                if (commanLine.Length > 7)
                {
                    if (commanLine.Substring(0, 6) == "%scene")
                    {
                        key = Convert.ToString(commanLine.Substring(7, commanLine.Length - 7));
                        keyfind = false;
                        if (key == "begin")
                        {
                            beginflag = true;
                        }
                        foreach (var itemdetail in outKey)
                        {
                            if (itemdetail == null)
                            {
                                continue;
                            }
                            string tempkey = itemdetail.ToString().Trim();
                            if (tempkey == key)
                            {
                                keyfind = true;
                            }
                        }
                        if (!keyfind)
                        {
                            outKey.Add(key);
                        }
                    }
                }
            }

            if (!beginflag)
            {
                errormsg = "未找到代码开始标志!";
                return -1;
            }

            return 0;
        }

        /// <summary>
        /// 获取脚本中变量的key值
        /// </summary>
        private static int getVarKey(ArrayList inlist, out ArrayList outKey, out string errormsg)
        {
            errormsg = string.Empty;
            outKey = new ArrayList();
            Boolean keyfind = false;
            string key = string.Empty; //分类
            foreach (var item in inlist)
            {
                if (item == null)
                {
                    continue;
                }
                string commanLine = item.ToString().Trim();
                if (string.IsNullOrEmpty(commanLine))
                {
                    continue;
                }

                switch (commanLine.Substring(0, 1))
                {
                    case "#"://注释
                    case "/"://注释
                    case "-"://注释
                        continue;
                    default:
                        break;
                }

                //判断区块标志
                if (commanLine.Length > 10)
                {
                    if (commanLine.Substring(0, 9) == "%variable")
                    {
                        key = Convert.ToString(commanLine.Substring(10, commanLine.Length - 10));
                        keyfind = false;
                        foreach (var itemdetail in outKey)
                        {
                            if (itemdetail == null)
                            {
                                continue;
                            }
                            string tempkey = itemdetail.ToString().Trim();
                            if (tempkey == key)
                            {
                                keyfind = true;
                            }
                        }
                        if (!keyfind)
                        {
                            outKey.Add(key);
                        }
                    }
                }
            }
            return 0;
        }

        /// <summary>
        /// 获取触发区块key值
        /// </summary>
        private static int getTriggerKey(ArrayList inlist, out ArrayList outKey, out string errormsg)
        {
            errormsg = string.Empty;
            outKey = new ArrayList();
            Boolean keyfind = false;
            string key = string.Empty; //分类
            foreach (var item in inlist)
            {
                if (item == null)
                {
                    continue;
                }
                string commanLine = item.ToString().Trim();
                if (string.IsNullOrEmpty(commanLine))
                {
                    continue;
                }

                switch (commanLine.Substring(0, 1))
                {
                    case "#"://注释
                    case "/"://注释
                    case "-"://注释
                        continue;
                    default:
                        break;
                }

                //判断区块标志
                if (commanLine.Length > 3)
                {
                    if (commanLine.Substring(0, 3) == "%bc")
                    {
                        key = Convert.ToString(commanLine.Substring(4, commanLine.Length - 4));
                        keyfind = false;
                        foreach (var itemdetail in outKey)
                        {
                            if (itemdetail == null)
                            {
                                continue;
                            }
                            string tempkey = itemdetail.ToString().Trim();
                            if (tempkey == key)
                            {
                                keyfind = true;
                            }
                        }
                        if (!keyfind)
                        {
                            outKey.Add(key);
                        }
                    }
                }
            }
            return 0;
        }

        /// <summary>
        /// 获取key值对应的value
        /// </summary>
        private static ArrayList spiltCommandList(string key, ArrayList inlist)
        {
            ArrayList value = new ArrayList();
            string listkey = string.Empty;

            foreach (var item in inlist)
            {
                if (item == null)
                {
                    continue;
                }
                string commanLine = item.ToString().Trim();

                //检查到触发区块标志则返回
                if (commanLine.Length > 3)
                {
                    if (commanLine.Substring(0, 3) == "%bc")
                    {
                        return value;
                    }
                }

                //判断区块标志
                if (commanLine.Length > 7)
                {
                    if (commanLine.Substring(0, 6) == "%scene")
                    {
                        listkey = Convert.ToString(commanLine.Substring(7, commanLine.Length - 7));
                        continue;
                    }
                }
                if (listkey == key)
                {
                    value.Add(commanLine);
                }
            }
            return value;
        }

        /// <summary>
        /// 获取变量key对应的value
        /// </summary>
        private static ArrayList spiltVarList(string key, ArrayList inlist)
        {
            ArrayList value = new ArrayList();
            string listkey = string.Empty;

            foreach (var item in inlist)
            {
                if (item == null)
                {
                    continue;
                }
                string commanLine = item.ToString().Trim();

                //变量快必须在区块前
                if (commanLine.Length > 7)
                {
                    if (commanLine.Substring(0, 6) == "%scene")
                    {
                        return value;
                    }
                }

                //判断区块标志
                if (commanLine.Length > 9)
                {
                    if (commanLine.Substring(0, 9) == "%variable")
                    {
                        listkey = Convert.ToString(commanLine.Substring(10, commanLine.Length - 10));
                        continue;
                    }
                }
                if (listkey == key)
                {
                    value.Add(commanLine);
                }
            }
            return value;
        }

        /// <summary>
        /// 获取触发区块key对应的value
        /// </summary>
        private static ArrayList spiltTriggerList(string key, ArrayList inlist)
        {
            ArrayList value = new ArrayList();
            string listkey = string.Empty;

            foreach (var item in inlist)
            {
                if (item == null)
                {
                    continue;
                }
                string commanLine = item.ToString().Trim();
                //判断区块标志
                if (commanLine.Length > 4)
                {
                    if (commanLine.Substring(0, 3) == "%bc")
                    {
                        listkey = Convert.ToString(commanLine.Substring(4, commanLine.Length - 4));
                        continue;
                    }
                }
                if (listkey == key)
                {
                    value.Add(commanLine);
                }
            }
            return value;
        }

        public static void FindMemoryValue(string key,int address)
        {

            if (processHandle == IntPtr.Zero)
            {
                Console.WriteLine("无法打开进程");
                return;
            }

            byte[] buffer = new byte[16];
            int bytesRead;
            bool result = ReadProcessMemory((int)processHandle, address, buffer, buffer.Length, out bytesRead);

            if (!result)
            {
                Console.WriteLine("无法读取内存");
            }
            else
            {
                switch (key)
                {
                    case "x":
                    case "y":
                        FindMemoryPoint(key, BitConverter.ToInt32(buffer, 0));
                        break;
                    case "m":
                    case "h":
                        FindMemoryhpandmp(key, BitConverter.ToInt32(buffer, 0));
                        break;
                    default:
                        gamevalue[key] = BitConverter.ToInt32(buffer, 0);
                        break;
                }
            }
        }

        /// <summary>
        /// 获取游戏x和y坐标
        /// </summary>
        /// <param name="key"></param>
        /// <param name="address"></param>
        public static void FindMemoryPoint(string key,int address)
        {
            int xpoint = address + 0x7c;
            int ypoint = address + 0x80;
            if (processHandle == IntPtr.Zero)
            {
                Console.WriteLine("无法打开进程");
                return;
            }

            byte[] buffer = new byte[4];
            int bytesRead;
            bool result = ReadProcessMemory((int)processHandle, xpoint, buffer, buffer.Length, out bytesRead);

            if (result)
            {
                gamevalue["x"] = BitConverter.ToInt32(buffer, 0);
            }

            byte[] buffery = new byte[4];
            int bytesReady;
            bool resulty = ReadProcessMemory((int)processHandle, ypoint, buffery, buffery.Length, out bytesReady);

            if (resulty)
            {
                gamevalue["y"] = BitConverter.ToInt32(buffery, 0);
            }
        }

        public static void FindMemoryhpandmp(string key, int address)
        {
            int hpoint = address + 0x510;
            int ypoint = address + 0x550;
            if (processHandle == IntPtr.Zero)
            {
                Console.WriteLine("无法打开进程");
                return;
            }

            byte[] buffer = new byte[4];
            int bytesRead;
            bool result = ReadProcessMemory((int)processHandle, hpoint, buffer, buffer.Length, out bytesRead);

            if (result)
            {
                gamevalue["h"] = BitConverter.ToInt32(buffer, 0);
            }

            byte[] buffery = new byte[4];
            int bytesReady;
            bool resulty = ReadProcessMemory((int)processHandle, ypoint, buffery, buffery.Length, out bytesReady);

            if (resulty)
            {
                gamevalue["m"] = BitConverter.ToInt32(buffery, 0);
            }
        }


        /// <summary>
        /// 获取指定路径脚本的代码
        /// </summary>
        public static int GetScript(string scriptpathname, out string errmsg)
        {
            errmsg = string.Empty;
            if (string.IsNullOrEmpty(scriptpathname))
            {
                errmsg = "代码路径为空!";
                return -1;
            }

            StreamReader objReader = new StreamReader(scriptpathname);
            string sLine = "";
            ArrayList LineList = new ArrayList();
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (string.IsNullOrEmpty(sLine))
                {
                    continue;
                }
                sLine = sLine.Trim();
                if (sLine == "")
                {
                    continue;
                }
                switch (sLine.Substring(0, 1))
                {
                    case "#"://注释
                    case "/"://注释
                    case "-"://注释
                        continue;
                    default:
                        break;
                }
                LineList.Add(sLine);
            }
            objReader.Close();

            if (LineList.Count <= 0)
            {
                errmsg = "代码内容为空!";
                return -1;
            }

            //获取区块key
            ArrayList key = new ArrayList();
            if (getCommandKey(LineList, out key, out errmsg) < 0)
            {
                return -1;
            }

            //获取变量key
            ArrayList varkey = new ArrayList();
            if (getVarKey(LineList, out varkey, out errmsg) < 0)
            {
                return -1;
            }

            //获取触发区块key
            ArrayList triggerKey = new ArrayList();
            if (getTriggerKey(LineList, out triggerKey, out errmsg) < 0)
            {
                return -1;
            }

            //获取区块代码
            cmdarraylist = new Dictionary<string, ArrayList>();
            varArrayList = new Dictionary<string, ArrayList>();
            varNumberList = new Dictionary<string, int>();
            foreach (var item in key)
            {
                ArrayList value = new ArrayList();
                cmdarraylist.Add(item.ToString(), spiltCommandList(item.ToString(), LineList));
            }

            //获取触发区块
            //触发区块代码
            triggerList = new Dictionary<string, ArrayList>();
            foreach (var item in triggerKey)
            {
                ArrayList value = new ArrayList();
                triggerList.Add(item.ToString(), spiltTriggerList(item.ToString(), LineList));
            }

            //获取变量明细
            varArrayList = new Dictionary<string, ArrayList>();
            foreach (var item in varkey)
            {
                ArrayList value = new ArrayList();
                varArrayList.Add(item.ToString(), spiltVarList(item.ToString(), LineList));
                //初始化变量下标
                AddvarNumber(item.ToString(), varArrayList[item.ToString()]);
            }

            return 0;
        }

        /// <summary>
        /// 修改变量下标
        /// </summary>
        private static void AddvarNumber(string key, ArrayList inlist)
        {
            int result = 0;

            if (!varNumberList.ContainsKey(key))
            {
                varNumberList.Add(key, result);
            }
            else
            {
                result = varNumberList[key] + 1;
                if (result >= inlist.Count)
                {
                    result = 0;
                }
                varNumberList[key] = result;
            }
        }

        /// <summary>
        /// 初始化变量
        /// </summary>
        public static void InitGameValue()
        {
            gamevalue = new Dictionary<string, int>();
            gamevalue.Add("m", 100);
            gamevalue.Add("M", 400);
            gamevalue.Add("h", 100);
            gamevalue.Add("H", 400);
            gamevalue.Add("x", 1);
            gamevalue.Add("y", 1);
            gamevalue.Add("targetx", 0);
            gamevalue.Add("targety", 0);
        }

        /// <summary>
        /// 初始化正则表达式
        /// </summary>
        public static void InitMathValue()
        {
            mathvalue = new Dictionary<int, string>();
        }




        /// <summary>
        /// 获取指定窗口句柄的内存地址
        /// </summary>
        public static int ReadProssmemory(IntPtr hWnd, string address)
        {
            byte[] bt = new byte[1024];
            int calcID;
            int dataAddress;
            string datastr;
            int readByte;
            ////由窗体句柄获得进程ID
            //GetWindowThreadProcessId(hWnd, out calcID);
            ////由进程ID获得进程句柄
            //int hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE, false, calcID);
            ////读取进程指定的内存地址

            ////ReadProcessMemory(hProcess, Convert.ToInt32(address, 16), out dataAddress, 2, out readByte);

            ////[DllImport("kernel32.dll ")]
            ////static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, byte[] lpBuffer, int nSize, out int lpNumberOfBytesRead); 

            //byte[] lpBuffer = new byte[255];
            //ReadProcessMemory(hProcess, Convert.ToInt32(address, 16), lpBuffer, 2, out readByte);
            //string str = System.Text.Encoding.Default.GetString(lpBuffer);
            dataAddress = 0;
            return dataAddress;
        }

        #region 鼠标命令
        /// <summary>
        /// 调用DLL鼠标移动
        /// </summary>
        private static void CallDmMouseMove(IntPtr hWnd, double x, double y)
        {
            int hwnd = (int)hWnd;

            if (prdm.IsBind(hwnd) != 1)
            {
                prdm.BindWindow(hwnd, "normal", "normal", "windows", 0); //绑定窗口
            }

            //dm.BindWindow(hwnd, "dx3", "windows3", "windows", 0); //画图后台点击成功
            //dm.BindWindow(hwnd, "normal", "normal", "normal", 0);

            if (x < 100)
            {
                x = x * 40;
            }

            if (y < 100)
            {
                y = y * 20;
            }

            if (x >= 800)
            {
                x = 785;
            }
            else if (x <= 0)
            {
                x = 2;
            }

            if (y >= 400)
            {
                //y = 385;
            }
            else if (y <= 0)
            {
                y = 2;
            }

            int inx = (int)x;
            int iny = (int)y;

            //相对坐标dm.MoveTo(617, 475);
            //绝对坐标dm.MoveTo(897,571);

            if (prdm.GetWindowState(hwnd, 1) != 1)
            {
                prdm.SetWindowState(hwnd, 1);//1: 激活指定窗口 7 :显示窗口
            }
            //dm.delay(100);
            prdm.MoveTo(inx, iny);
            //dm.delay(100);
            truedelay(0.1);
            prdm.LeftClick();
            truedelay(0.1);
            prdm.LeftClick();
            truedelay(0.2);
        }

        private static void CallDmMouseKill(IntPtr hWnd, double x, double y)
        {
            int hwnd = (int)hWnd;

            if (prdm.IsBind(hwnd) != 1)
            {
                prdm.BindWindow(hwnd, "normal", "normal", "windows", 0); //绑定窗口
            }

            //dm.BindWindow(hwnd, "dx3", "windows3", "windows", 0); //画图后台点击成功
            //dm.BindWindow(hwnd, "normal", "normal", "normal", 0);

            if (x < 100)
            {
                x = x * 40;
            }

            if (y < 100)
            {
                y = y * 20;
            }

            if (x >= 800)
            {
                x = 785;
            }
            else if (x <= 0)
            {
                x = 2;
            }

            if (y >= 400)
            {
                //y = 385;
            }
            else if (y <= 0)
            {
                y = 2;
            }

            int inx = (int)x;
            int iny = (int)y;

            //相对坐标dm.MoveTo(617, 475);
            //绝对坐标dm.MoveTo(897,571);

            if (prdm.GetWindowState(hwnd, 1) != 1)
            {
                prdm.SetWindowState(hwnd, 1);//1: 激活指定窗口 7 :显示窗口
            }

            //dm.delay(100);
            prdm.MoveTo(inx, iny);
            //dm.delay(100);
            Thread.Sleep(100);
            prdm.KeyPressChar("F1");

            truedelay(0.6);
            //dm.delay(100);
            prdm.LeftClick();
            truedelay(0.6);
            //dm.delay(100);
            //Thread.Sleep(500);
            //dm.SetWindowState(hwnd, 2); //最小化指定窗口,但不激活
        }

        /// <summary>
        /// 按下鼠标左键
        /// </summary>
        private static void CallDmMouseLeftDown()
        {
            prdm.LeftDown();
        }

        /// <summary>
        /// 抬起鼠标左键
        /// </summary>
        private static void CallDmMouseLeftUp()
        {
            prdm.LeftUp();
        }

        /// <summary>
        /// 按下鼠标右键
        /// </summary>
        private static void CallDmRightDown()
        {
            prdm.RightDown();
        }

        /// <summary>
        /// 抬起鼠标右键
        /// </summary>
        private static void CallDmRightUp()
        {
            prdm.RightUp();
        }

        /// <summary>
        /// 左键单击
        /// </summary>
        private static void CallDmLeftClick()
        {
            prdm.LeftClick();
        }

        #endregion

        /// <summary>
        /// 按住按键
        /// </summary>
        /// <param name="keycode"></param>
        /// <returns></returns>
        private static void CallDmKeyDown(string keycode)
        {
            prdm.KeyDownChar(keycode);
        }

        /// <summary>
        /// 放开按键
        /// </summary>
        /// <param name="keycode"></param>
        /// <returns></returns>
        private static void CallDmKeyUP(string keycode)
        {
            prdm.KeyUpChar(keycode);
        }

        private static void CallDmKeyPress(string keystr)
        {
            prdm.KeyPressChar(keystr);
        }

        private static void CallDmKeyDown(int keystr)
        {
            prdm.KeyDown(keystr);
        }

        public static IntPtr getmsghandle(out IntPtr outparenthwnd, string id)
        {
            outparenthwnd = IntPtr.Zero;
            string proname = "iKing Messages [" + id + "]";
            IntPtr hwndAfter = FindWindowEx((IntPtr)0, (IntPtr)0, "KKChatWindow", proname);
            outparenthwnd = hwndAfter;
            if (hwndAfter != IntPtr.Zero)
            {
                msgHwnd = hwndAfter;
                IntPtr childHwnd = FindWindowEx(hwndAfter, IntPtr.Zero, "RICHEDIT50W", string.Empty);


                //发送消息框
                SendWnd = FindWindowEx(hwndAfter, childHwnd, "RICHEDIT50W", string.Empty);

                return childHwnd;
            }

            return hwndAfter;

        }

        public static IntPtr getMasterhandle(out IntPtr outparenthwnd, string id)
        {
            string proname = "iKing [" + id + "]";
            IntPtr hwndAfter = FindWindowEx((IntPtr)0, (IntPtr)0, null, proname);
            outparenthwnd = hwndAfter;
            return hwndAfter;

        }


        /// <summary>
        ///  释放资源
        /// </summary>
        public static void dmDispose()
        {
            if (prdm != null)
            {
                if (prdm.IsBind((int)programhWnd) == 1)
                {
                    prdm.UnBindWindow();
                    prdm.Dispose();
                    prdm = null;
                }
            }
        }

        /// <summary>
        /// 替换命令中变量
        /// </summary>
        /// <param name="cmdstring"></param>
        /// <returns></returns>
        private static string replacecmdmsg(string commandtmp)
        {
            int findpos = 0;
            int startpos = 0;

            #region 替换 坐标 %x 和%y,%m 当前魔法, %h 当前生命

            //先获取游戏内部的坐标和mp
            GetGameVaue();

            findpos = commandtmp.IndexOf("%x", 0);
            while (findpos > 0)
            {
                commandtmp = commandtmp.Replace("%x", gamevalue["x"].ToString());
                findpos = commandtmp.IndexOf("%x", 0);
            }

            findpos = commandtmp.IndexOf("%y", 0);
            while (findpos > 0)
            {
                commandtmp = commandtmp.Replace("%y", gamevalue["y"].ToString());
                findpos = commandtmp.IndexOf("%y", 0);
            }

            findpos = commandtmp.IndexOf("%m", 0);
            while (findpos > 0)
            {
                commandtmp = commandtmp.Replace("%m", gamevalue["m"].ToString());
                findpos = commandtmp.IndexOf("%m", 0);
            }

            findpos = commandtmp.IndexOf("%h", 0);
            while (findpos > 0)
            {
                commandtmp = commandtmp.Replace("%h", gamevalue["h"].ToString());
                findpos = commandtmp.IndexOf("%h", 0);
            }
            #endregion


            #region 取值并变量下标 %i
            findpos = commandtmp.IndexOf("%i", 0);

            if (findpos > 0)
            {
                //替换循环变量
                foreach (string _key in varArrayList.Keys)
                {
                    //普通变量替换
                    findpos = commandtmp.IndexOf("%i" + _key, 0);
                    while (findpos > 0)
                    {
                        commandtmp = commandtmp.Replace("%i" + _key, varArrayList[_key][varNumberList[_key]].ToString());
                        AddvarNumber(_key, varArrayList[_key]);
                        findpos = commandtmp.IndexOf("%i" + _key, 0);
                    }
                }
            }
            #endregion

            #region 增加普通变量只取值 %v
            findpos = commandtmp.IndexOf("%v", 0);

            if (findpos > 0)
            {
                //替换循环变量
                foreach (string _key in varArrayList.Keys)
                {
                    //普通变量替换
                    findpos = commandtmp.IndexOf("%v" + _key, 0);
                    while (findpos > 0)
                    {
                        commandtmp = commandtmp.Replace("%v" + _key, varArrayList[_key][varNumberList[_key]].ToString());
                        findpos = commandtmp.IndexOf("%v" + _key, 0);
                    }
                }
            }
            #endregion

            #region 地址变量替换,并变量递增 %p,%p
            startpos = commandtmp.IndexOf("%p", 0);
            string basecoordinate = string.Empty;
            string addcoordinate = string.Empty;
            if (startpos > 0)
            {
                int endpos = commandtmp.IndexOf("%p", startpos + 1);
                if (endpos > 0)
                {
                    findpos = commandtmp.IndexOf(",", 0);

                    if (findpos > 0)
                    {

                        int otherpos = commandtmp.IndexOf(" ", endpos);
                        string othercmd = string.Empty;
                        if (otherpos > 0)
                        {
                            othercmd = commandtmp.Substring(otherpos);
                            addcoordinate = commandtmp.Substring(findpos + 3, otherpos - endpos - 2).Trim();
                        }
                        else
                        {
                            othercmd = "";
                            addcoordinate = commandtmp.Substring(findpos + 3).Trim();
                        }
                        basecoordinate = commandtmp.Substring(startpos + 2, findpos - startpos - 2).Trim();
                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == basecoordinate)
                            {
                                basecoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                AddvarNumber(_key, varArrayList[_key]);
                                break;
                            }
                        }

                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == addcoordinate)
                            {
                                addcoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                addcoordinate = addcoordinate.Replace("(", "").Trim();
                                addcoordinate = addcoordinate.Replace(")", "").Trim();
                                AddvarNumber(_key, varArrayList[_key]);
                                break;
                            }
                        }

                        if (!(string.IsNullOrEmpty(basecoordinate) || string.IsNullOrEmpty(addcoordinate)))
                        {
                            int posstart = basecoordinate.IndexOf(",", 0);
                            if (posstart > 0)
                            {
                                int posend = addcoordinate.IndexOf(",", 0);

                                if (endpos > 0)
                                {
                                    int bposx = Convert.ToInt32(basecoordinate.Remove(posstart));
                                    int bosy = Convert.ToInt32(basecoordinate.Substring(posstart + 1));
                                    int aposx = Convert.ToInt32(addcoordinate.Remove(posend));
                                    int aosy = Convert.ToInt32(addcoordinate.Substring(posend + 1));
                                    string addres = ((bposx + aposx - 5) * 65536 + bosy + aosy - 10).ToString();

                                    commandtmp = commandtmp.Remove(startpos) + addres + othercmd;
                                }

                            }
                        }
                    }
                }
            }
            #endregion

            #region 地址变量替换,变量不变化 %b,%b
            startpos = commandtmp.IndexOf("%b", 0);
            basecoordinate = string.Empty;
            addcoordinate = string.Empty;
            if (startpos > 0)
            {
                int endpos = commandtmp.IndexOf("%b", startpos + 1);
                if (endpos > 0)
                {
                    findpos = commandtmp.IndexOf(",", 0);

                    if (findpos > 0)
                    {

                        int otherpos = commandtmp.IndexOf(" ", endpos);
                        string othercmd = string.Empty;
                        if (otherpos > 0)
                        {
                            othercmd = commandtmp.Substring(otherpos);
                            addcoordinate = commandtmp.Substring(findpos + 3, otherpos - endpos - 2).Trim();
                        }
                        else
                        {
                            othercmd = "";
                            addcoordinate = commandtmp.Substring(findpos + 3).Trim();
                        }
                        basecoordinate = commandtmp.Substring(startpos + 2, findpos - startpos - 2).Trim();
                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == basecoordinate)
                            {
                                basecoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                break;
                            }
                        }

                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == addcoordinate)
                            {
                                addcoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                addcoordinate = addcoordinate.Replace("(", "").Trim();
                                addcoordinate = addcoordinate.Replace(")", "").Trim();
                                break;
                            }
                        }

                        if (!(string.IsNullOrEmpty(basecoordinate) || string.IsNullOrEmpty(addcoordinate)))
                        {
                            int posstart = basecoordinate.IndexOf(",", 0);
                            if (posstart > 0)
                            {
                                int posend = addcoordinate.IndexOf(",", 0);

                                if (endpos > 0)
                                {
                                    int bposx = Convert.ToInt32(basecoordinate.Remove(posstart));
                                    int bosy = Convert.ToInt32(basecoordinate.Substring(posstart + 1));
                                    int aposx = Convert.ToInt32(addcoordinate.Remove(posend));
                                    int aosy = Convert.ToInt32(addcoordinate.Substring(posend + 1));
                                    string addres = ((bposx + aposx - 5) * 65536 + bosy + aosy - 10).ToString();

                                    commandtmp = commandtmp.Remove(startpos) + addres + othercmd;
                                }

                            }
                        }
                    }
                }
            }
            #endregion

            #region 地址变量替换,第一个不变化,第二个变化 %b,%p
            startpos = commandtmp.IndexOf("%b", 0);
            basecoordinate = string.Empty;
            addcoordinate = string.Empty;
            if (startpos > 0)
            {
                int endpos = commandtmp.IndexOf("%p", startpos + 1);
                if (endpos > 0)
                {
                    findpos = commandtmp.IndexOf(",", 0);

                    if (findpos > 0)
                    {

                        int otherpos = commandtmp.IndexOf(" ", endpos);
                        string othercmd = string.Empty;
                        if (otherpos > 0)
                        {
                            othercmd = commandtmp.Substring(otherpos);
                            addcoordinate = commandtmp.Substring(findpos + 3, otherpos - endpos - 2).Trim();
                        }
                        else
                        {
                            othercmd = "";
                            addcoordinate = commandtmp.Substring(findpos + 3).Trim();
                        }
                        basecoordinate = commandtmp.Substring(startpos + 2, findpos - startpos - 2).Trim();
                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == basecoordinate)
                            {
                                basecoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                break;
                            }
                        }

                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == addcoordinate)
                            {
                                addcoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                addcoordinate = addcoordinate.Replace("(", "").Trim();
                                addcoordinate = addcoordinate.Replace(")", "").Trim();
                                AddvarNumber(_key, varArrayList[_key]);
                                break;
                            }
                        }

                        if (!(string.IsNullOrEmpty(basecoordinate) || string.IsNullOrEmpty(addcoordinate)))
                        {
                            int posstart = basecoordinate.IndexOf(",", 0);
                            if (posstart > 0)
                            {
                                int posend = addcoordinate.IndexOf(",", 0);

                                if (endpos > 0)
                                {
                                    int bposx = Convert.ToInt32(basecoordinate.Remove(posstart));
                                    int bosy = Convert.ToInt32(basecoordinate.Substring(posstart + 1));
                                    int aposx = Convert.ToInt32(addcoordinate.Remove(posend));
                                    int aosy = Convert.ToInt32(addcoordinate.Substring(posend + 1));
                                    string addres = ((bposx + aposx - 5) * 65536 + bosy + aosy - 10).ToString();

                                    commandtmp = commandtmp.Remove(startpos) + addres + othercmd;
                                }

                            }
                        }
                    }
                }
            }
            #endregion

            #region 地址变量替换,第一个变化,第二个不变化 %p,%b
            startpos = commandtmp.IndexOf("%p", 0);
            basecoordinate = string.Empty;
            addcoordinate = string.Empty;
            if (startpos > 0)
            {
                int endpos = commandtmp.IndexOf("%b", startpos + 1);
                if (endpos > 0)
                {
                    findpos = commandtmp.IndexOf(",", 0);

                    if (findpos > 0)
                    {

                        int otherpos = commandtmp.IndexOf(" ", endpos);
                        string othercmd = string.Empty;
                        if (otherpos > 0)
                        {
                            othercmd = commandtmp.Substring(otherpos);
                            addcoordinate = commandtmp.Substring(findpos + 3, otherpos - endpos - 2).Trim();
                        }
                        else
                        {
                            othercmd = "";
                            addcoordinate = commandtmp.Substring(findpos + 3).Trim();
                        }
                        basecoordinate = commandtmp.Substring(startpos + 2, findpos - startpos - 2).Trim();
                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == basecoordinate)
                            {
                                basecoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                AddvarNumber(_key, varArrayList[_key]);
                                break;
                            }
                        }

                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == addcoordinate)
                            {
                                addcoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                addcoordinate = addcoordinate.Replace("(", "").Trim();
                                addcoordinate = addcoordinate.Replace(")", "").Trim();
                                break;
                            }
                        }

                        if (!(string.IsNullOrEmpty(basecoordinate) || string.IsNullOrEmpty(addcoordinate)))
                        {
                            int posstart = basecoordinate.IndexOf(",", 0);
                            if (posstart > 0)
                            {
                                int posend = addcoordinate.IndexOf(",", 0);

                                if (endpos > 0)
                                {
                                    int bposx = Convert.ToInt32(basecoordinate.Remove(posstart));
                                    int bosy = Convert.ToInt32(basecoordinate.Substring(posstart + 1));
                                    int aposx = Convert.ToInt32(addcoordinate.Remove(posend));
                                    int aosy = Convert.ToInt32(addcoordinate.Substring(posend + 1));
                                    string addres = ((bposx + aposx - 5) * 65536 + bosy + aosy - 10).ToString();

                                    commandtmp = commandtmp.Remove(startpos) + addres + othercmd;
                                }

                            }
                        }
                    }
                }
            }
            #endregion

            #region 国家地址替换,并变量递增 %k,%k
            startpos = commandtmp.IndexOf("%k", 0);
            basecoordinate = string.Empty;
            addcoordinate = string.Empty;
            if (startpos > 0)
            {
                int endpos = commandtmp.IndexOf("%k", startpos + 1);
                if (endpos > 0)
                {
                    findpos = commandtmp.IndexOf(",", 0);

                    if (findpos > 0)
                    {

                        int otherpos = commandtmp.IndexOf(" ", endpos);
                        string othercmd = string.Empty;
                        if (otherpos > 0)
                        {
                            othercmd = commandtmp.Substring(otherpos);
                            addcoordinate = commandtmp.Substring(findpos + 3, otherpos - endpos - 2).Trim();
                        }
                        else
                        {
                            othercmd = "";
                            addcoordinate = commandtmp.Substring(findpos + 3).Trim();
                        }
                        basecoordinate = commandtmp.Substring(startpos + 2, findpos - startpos - 2).Trim();
                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == basecoordinate)
                            {
                                basecoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                AddvarNumber(_key, varArrayList[_key]);
                                break;
                            }
                        }

                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == addcoordinate)
                            {
                                addcoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                addcoordinate = addcoordinate.Replace("(", "").Trim();
                                addcoordinate = addcoordinate.Replace(")", "").Trim();
                                AddvarNumber(_key, varArrayList[_key]);
                                break;
                            }
                        }

                        if (!(string.IsNullOrEmpty(basecoordinate) || string.IsNullOrEmpty(addcoordinate)))
                        {
                            int posstart = basecoordinate.IndexOf(",", 0);
                            if (posstart > 0)
                            {
                                int posend = addcoordinate.IndexOf(",", 0);

                                if (endpos > 0)
                                {
                                    int bposx = Convert.ToInt32(basecoordinate.Remove(posstart));
                                    int bosy = Convert.ToInt32(basecoordinate.Substring(posstart + 1));
                                    int aposx = Convert.ToInt32(addcoordinate.Remove(posend));
                                    int aosy = Convert.ToInt32(addcoordinate.Substring(posend + 1));
                                    string addres = ((bposx + aposx - 5) * 10000 + bosy + aosy - 10).ToString();

                                    commandtmp = commandtmp.Remove(startpos) + addres + othercmd;
                                }

                            }
                        }
                    }
                }
            }
            #endregion

            #region 国家地址替换,变量不变化 %g,%g
            startpos = commandtmp.IndexOf("%g", 0);
            basecoordinate = string.Empty;
            addcoordinate = string.Empty;
            if (startpos > 0)
            {
                int endpos = commandtmp.IndexOf("%g", startpos + 1);
                if (endpos > 0)
                {
                    findpos = commandtmp.IndexOf(",", 0);

                    if (findpos > 0)
                    {

                        int otherpos = commandtmp.IndexOf(" ", endpos);
                        string othercmd = string.Empty;
                        if (otherpos > 0)
                        {
                            othercmd = commandtmp.Substring(otherpos);
                            addcoordinate = commandtmp.Substring(findpos + 3, otherpos - endpos - 2).Trim();
                        }
                        else
                        {
                            othercmd = "";
                            addcoordinate = commandtmp.Substring(findpos + 3).Trim();
                        }
                        basecoordinate = commandtmp.Substring(startpos + 2, findpos - startpos - 2).Trim();
                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == basecoordinate)
                            {
                                basecoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                break;
                            }
                        }

                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == addcoordinate)
                            {
                                addcoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                addcoordinate = addcoordinate.Replace("(", "").Trim();
                                addcoordinate = addcoordinate.Replace(")", "").Trim();
                                break;
                            }
                        }

                        if (!(string.IsNullOrEmpty(basecoordinate) || string.IsNullOrEmpty(addcoordinate)))
                        {
                            int posstart = basecoordinate.IndexOf(",", 0);
                            if (posstart > 0)
                            {
                                int posend = addcoordinate.IndexOf(",", 0);

                                if (endpos > 0)
                                {
                                    int bposx = Convert.ToInt32(basecoordinate.Remove(posstart));
                                    int bosy = Convert.ToInt32(basecoordinate.Substring(posstart + 1));
                                    int aposx = Convert.ToInt32(addcoordinate.Remove(posend));
                                    int aosy = Convert.ToInt32(addcoordinate.Substring(posend + 1));
                                    string addres = ((bposx + aposx - 5) * 10000 + bosy + aosy - 10).ToString();

                                    commandtmp = commandtmp.Remove(startpos) + addres + othercmd;
                                }

                            }
                        }
                    }
                }
            }
            #endregion

            #region 国家地址替换,第一个不变化,第二个变化 %g,%k
            startpos = commandtmp.IndexOf("%g", 0);
            basecoordinate = string.Empty;
            addcoordinate = string.Empty;
            if (startpos > 0)
            {
                int endpos = commandtmp.IndexOf("%k", startpos + 1);
                if (endpos > 0)
                {
                    findpos = commandtmp.IndexOf(",", 0);

                    if (findpos > 0)
                    {

                        int otherpos = commandtmp.IndexOf(" ", endpos);
                        string othercmd = string.Empty;
                        if (otherpos > 0)
                        {
                            othercmd = commandtmp.Substring(otherpos);
                            addcoordinate = commandtmp.Substring(findpos + 3, otherpos - endpos - 2).Trim();
                        }
                        else
                        {
                            othercmd = "";
                            addcoordinate = commandtmp.Substring(findpos + 3).Trim();
                        }
                        basecoordinate = commandtmp.Substring(startpos + 2, findpos - startpos - 2).Trim();
                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == basecoordinate)
                            {
                                basecoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                break;
                            }
                        }

                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == addcoordinate)
                            {
                                addcoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                addcoordinate = addcoordinate.Replace("(", "").Trim();
                                addcoordinate = addcoordinate.Replace(")", "").Trim();
                                AddvarNumber(_key, varArrayList[_key]);
                                break;
                            }
                        }

                        if (!(string.IsNullOrEmpty(basecoordinate) || string.IsNullOrEmpty(addcoordinate)))
                        {
                            int posstart = basecoordinate.IndexOf(",", 0);
                            if (posstart > 0)
                            {
                                int posend = addcoordinate.IndexOf(",", 0);

                                if (endpos > 0)
                                {
                                    int bposx = Convert.ToInt32(basecoordinate.Remove(posstart));
                                    int bosy = Convert.ToInt32(basecoordinate.Substring(posstart + 1));
                                    int aposx = Convert.ToInt32(addcoordinate.Remove(posend));
                                    int aosy = Convert.ToInt32(addcoordinate.Substring(posend + 1));
                                    string addres = ((bposx + aposx - 5) * 10000 + bosy + aosy - 10).ToString();

                                    commandtmp = commandtmp.Remove(startpos) + addres + othercmd;
                                }

                            }
                        }
                    }
                }
            }
            #endregion

            #region 国家地址替换,第一个变化,第二个不变化 %k,%g
            startpos = commandtmp.IndexOf("%k", 0);
            basecoordinate = string.Empty;
            addcoordinate = string.Empty;
            if (startpos > 0)
            {
                int endpos = commandtmp.IndexOf("%g", startpos + 1);
                if (endpos > 0)
                {
                    findpos = commandtmp.IndexOf(",", 0);

                    if (findpos > 0)
                    {

                        int otherpos = commandtmp.IndexOf(" ", endpos);
                        string othercmd = string.Empty;
                        if (otherpos > 0)
                        {
                            othercmd = commandtmp.Substring(otherpos);
                            addcoordinate = commandtmp.Substring(findpos + 3, otherpos - endpos - 2).Trim();
                        }
                        else
                        {
                            othercmd = "";
                            addcoordinate = commandtmp.Substring(findpos + 3).Trim();
                        }
                        basecoordinate = commandtmp.Substring(startpos + 2, findpos - startpos - 2).Trim();
                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == basecoordinate)
                            {
                                basecoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                AddvarNumber(_key, varArrayList[_key]);
                                break;
                            }
                        }

                        foreach (string _key in varArrayList.Keys)
                        {
                            if (_key == addcoordinate)
                            {
                                addcoordinate = varArrayList[_key][varNumberList[_key]].ToString();
                                addcoordinate = addcoordinate.Replace("(", "").Trim();
                                addcoordinate = addcoordinate.Replace(")", "").Trim();
                                break;
                            }
                        }

                        if (!(string.IsNullOrEmpty(basecoordinate) || string.IsNullOrEmpty(addcoordinate)))
                        {
                            int posstart = basecoordinate.IndexOf(",", 0);
                            if (posstart > 0)
                            {
                                int posend = addcoordinate.IndexOf(",", 0);

                                if (endpos > 0)
                                {
                                    int bposx = Convert.ToInt32(basecoordinate.Remove(posstart));
                                    int bosy = Convert.ToInt32(basecoordinate.Substring(posstart + 1));
                                    int aposx = Convert.ToInt32(addcoordinate.Remove(posend));
                                    int aosy = Convert.ToInt32(addcoordinate.Substring(posend + 1));
                                    string addres = ((bposx + aposx - 5) * 10000 + bosy + aosy - 10).ToString();

                                    commandtmp = commandtmp.Remove(startpos) + addres + othercmd;
                                }

                            }
                        }
                    }
                }
            }
            #endregion

            #region 正则判断变量 %0 -> %9
            for (int i = 1; i < 26; i++)
            {
                findpos = commandtmp.IndexOf("%" + i, 0);

                if (findpos > 0)
                {
                    //替换循环变量
                    foreach (var item in mathvalue)
                    {
                        if (item.Key == i)
                        {
                            commandtmp = commandtmp.Replace("%" + item.Key, item.Value);
                        }
                    }
                }
            }

            #endregion


            return commandtmp;
        }

        /// <summary>
        /// 获取服务器返回消息
        /// </summary>
        /// <param name="hWnd"></param>
        public static ArrayList analysisRespense(IntPtr hWnd)
        {
            getrich rich = new getrich();

            string _segmentSeparator = "\n";
            string _fieldSeparator = "\r";

            string tmp = rich.Process_ReadRichEditText(hWnd);

            string[] rowSeparator = { _segmentSeparator, _fieldSeparator };
            string[] hl7Rows = tmp.Split(rowSeparator, StringSplitOptions.RemoveEmptyEntries);	//hl7数据串按行（段）分割的集合

            ArrayList getmsg = new ArrayList();

            foreach (string row in hl7Rows)
            {
                string strRemove = row;
                if (string.IsNullOrEmpty(strRemove))
                {
                    continue;
                }

                if (row.Length < 3)
                {
                    continue;
                }

                if (row.Substring(0, 2) == ">>")
                {
                    strRemove = strRemove.Remove(0, 2);
                    if (getmsg.Count > 0)
                    {
                        getmsg[getmsg.Count - 1] += strRemove;
                        continue;
                    }
                }

                getmsg.Add(strRemove);
            }

            ArrayList analysismsg = new ArrayList();

            int count = 0;
            foreach (string item in getmsg)
            {
                count++;
                if (responsemsg == null)
                {
                    analysismsg.Add(item.ToString());
                }
                else
                {
                    if (count <= responsemsg.Count)
                    {
                        continue;
                    }
                    analysismsg.Add(item.ToString());
                }

            }
            responsemsg = getmsg;

            GetServerDefault(analysismsg);

            return analysismsg;

        }

        private static void GetServerDefault(ArrayList analysismsg)
        {
            foreach (string item in analysismsg)
            {
                #region 判断坐标
                //现在所在的位置大约是在 (169, 391) 
                if (System.Text.RegularExpressions.Regex.IsMatch(item, @"现在所在的位置大约是在*"))
                {
                    int pos = item.IndexOf(")", 0);
                    if (pos > 0)
                    {
                        pos = item.IndexOf("(", pos);

                        int endpos = item.IndexOf(",", pos);
                        if (endpos > 0)
                        {
                            string rmp = item.Substring(pos + "(".Length, endpos - pos - "(".Length);
                            gamevalue["x"] = Convert.ToInt32(rmp);
                            pos = endpos;
                            endpos = item.IndexOf(")", pos + 1);
                            if (endpos > 0)
                            {
                                rmp = item.Substring(pos + ",".Length, endpos - pos - ",".Length);
                                gamevalue["y"] = Convert.ToInt32(rmp);
                            }
                        }
                    }

                }



                #endregion

                #region 简体hp,mp判断
                //item.IndexOf("【", 0) > 0 && 
                if (item.IndexOf("战斗经验", 0) > 0 && item.IndexOf("右手武器等级", 0) > 0)
                {
                    int pos = item.IndexOf("<体力>", 0);
                    if (pos > 0)
                    {
                        int startpos = item.IndexOf("/", pos + 1);
                        if (startpos > 0)
                        {
                            string rmp = item.Substring(pos + "<体力>".Length, startpos - pos - "<体力>".Length);
                            gamevalue["h"] = Convert.ToInt32(rmp);
                            int maxhpos = item.IndexOf("<", startpos + 1);
                            if (maxhpos > 0)
                            {
                                gamevalue["H"] = Convert.ToInt32(item.Substring(startpos + 1, maxhpos - startpos - 1));
                                startpos = item.IndexOf(">", maxhpos);
                                if (startpos > 0)
                                {
                                    pos = item.IndexOf("/", startpos);
                                    if (pos > 0)
                                    {
                                        gamevalue["m"] = Convert.ToInt32(item.Substring(startpos + 1, pos - startpos - 1));
                                        int endpos = item.IndexOf("右手武器等级", pos + 1);
                                        if (endpos > 0)
                                        {
                                            gamevalue["M"] = Convert.ToInt32(item.Substring(pos + 1, endpos - pos - 1));
                                        }
                                        //titlename = "生命 = " + gamevalue["h"].ToString() + "法力" + gamevalue["m"].ToString();
                                        //ChangeTitle();
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion

                #region 繁体hp,mp判断
                //item.IndexOf("【", 0) > 0 && 
                if (item.IndexOf("戰鬥經驗", 0) > 0 && item.IndexOf("右手武器等級", 0) > 0)
                {
                    int pos = item.IndexOf("<體力>", 0);
                    if (pos > 0)
                    {
                        int startpos = item.IndexOf("/", pos + 1);
                        if (startpos > 0)
                        {
                            string rmp = item.Substring(pos + "<體力>".Length, startpos - pos - "<體力>".Length);
                            gamevalue["h"] = Convert.ToInt32(rmp);
                            int maxhpos = item.IndexOf("<", startpos + 1);
                            if (maxhpos > 0)
                            {
                                gamevalue["H"] = Convert.ToInt32(item.Substring(startpos + 1, maxhpos - startpos - 1));
                                startpos = item.IndexOf(">", maxhpos);
                                if (startpos > 0)
                                {
                                    pos = item.IndexOf("/", startpos);
                                    if (pos > 0)
                                    {
                                        gamevalue["m"] = Convert.ToInt32(item.Substring(startpos + 1, pos - startpos - 1));
                                        int endpos = item.IndexOf("右手武器等級", pos + 1);
                                        if (endpos > 0)
                                        {
                                            gamevalue["M"] = Convert.ToInt32(item.Substring(pos + 1, endpos - pos - 1));
                                        }
                                        //titlename = "生命 = " + gamevalue["h"].ToString() + "法力" + gamevalue["m"].ToString();
                                        //ChangeTitle();
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion
            }
        }

        /// <summary>
        /// 判断服务器返回信息
        /// </summary>
        public static int checkResponse(ArrayList inmsg, string checkmsg)
        {
            if (inmsg == null)
            {
                return 0;
            }
            foreach (string item in inmsg)
            {
                string instr = item.ToString().Trim();

                #region 原来固定写死代码
                /*
                string checkstr = "你如果同意，请打 organ accept ";
                string removestr = "你如果同意，请打 ";

                if (instr.Length > checkstr.Length)
                {
                    if (instr.Substring(0, checkstr.Length) == checkstr)
                    {
                        instr = instr.Remove(0, removestr.Length);
                        tmpsenmsg(instr);
                        continue;
                    }
                }

                //月神的恩泽(tie)告诉你 : 收我
                int pos = instr.IndexOf("告诉你 : 收我", 0);

                if (pos > 0)
                {
                    int start = instr.IndexOf("(", 0);
                    int end = instr.IndexOf(")", 0);
                    if (start > 0 && end > 0)
                    {
                        instr = instr.Substring(start + 1, end - start - 1);
                        instr = "accept " + instr;
                        tmpsenmsg(instr);
                        continue;
                    }
                }

                pos = instr.IndexOf("告诉你 : shouwo", 0);

                if (pos > 0)
                {
                    int start = instr.IndexOf("(", 0);
                    int end = instr.IndexOf(")", 0);
                    if (start > 0 && end > 0)
                    {
                        instr = instr.Substring(start + 1, end - start - 1);
                        instr = "accept " + instr;
                        tmpsenmsg(instr);
                        continue;
                    }
                }

                pos = 0;
                //【月神教区】月神的恩泽(tie)﹕开我
                pos = instr.IndexOf("月神教区", 0);

                if (pos > 0)
                {
                    pos = 0;
                    pos = instr.IndexOf("﹕开我", 0);
                    if (pos > 0)
                    {
                        int start = instr.IndexOf("(", 0);
                        int end = instr.IndexOf(")", 0);
                        if (start > 0 && end > 0)
                        {
                            instr = instr.Substring(start + 1, end - start - 1);
                            instr = "banish " + instr;
                            tmpsenmsg(instr);
                            continue;
                        }
                    }
                }

                pos = instr.IndexOf("装备之国", 0);

                if (pos > 0)
                {
                    pos = 0;
                    pos = instr.IndexOf("﹕kaiwo", 0);
                    if (pos > 0)
                    {
                        int start = instr.IndexOf("(", 0);
                        int end = instr.IndexOf(")", 0);
                        if (start > 0 && end > 0)
                        {
                            instr = instr.Substring(start + 1, end - start - 1);
                            instr = "banish " + instr;
                            tmpsenmsg(instr);
                            continue;
                        }
                    }
                }

                pos = instr.IndexOf("梦之都", 0);

                if (pos > 0)
                {
                    pos = 0;
                    pos = instr.IndexOf("﹕kaiwo", 0);
                    if (pos > 0)
                    {
                        int start = instr.IndexOf("(", 0);
                        int end = instr.IndexOf(")", 0);
                        if (start > 0 && end > 0)
                        {
                            instr = instr.Substring(start + 1, end - start - 1);
                            instr = "banish " + instr;
                            tmpsenmsg(instr);
                            continue;
                        }
                    }
                }

                pos = 0;
                //圣龙帝国(A_shenglong)的「收人中，请支持」圣龙天剑(shenglong)要求和贵国建立同盟关系。
                pos = instr.IndexOf("要求和贵国建立同盟关系。", 0);

                if (pos > 0)
                {
                    pos = 0;
                    pos = instr.IndexOf(")的", 0);
                    if (pos > 0)
                    {
                        int start = instr.IndexOf("(", 0);
                        int end = instr.IndexOf(")", 0);
                        if (start > 0 && end > 0)
                        {
                            instr = instr.Substring(start + 1, end - start - 1);
                            instr = "ally with " + instr;
                            tmpsenmsg(instr.ToLower());
                            continue;
                        }
                    }
                }
                */
                #endregion

                if (instr == checkmsg)
                {
                    return 1;
                }

                //正则表达式匹配
                if (InputMatches(instr, checkmsg))
                {
                    return 1;
                }

                //模拟匹配
                if (System.Text.RegularExpressions.Regex.IsMatch(instr, checkmsg))
                {
                    return 1; //匹配成功
                }
            }
            return 0;
        }

        public static void GetGameVaue()
        {
            //获取的x坐标,会同时获取y的坐标
            string memorykey = Properties.Settings.Default.Memory_x;
            FindMemoryValue("x", Convert.ToInt32(memorykey, 16));

            ////获取的y坐标
            //memorykey = Properties.Settings.Default.Memory_y;
            //FindMemoryValue("y", Convert.ToInt32(memorykey, 16));

            //获取的当前mp,hp
            memorykey = Properties.Settings.Default.Memory_m;
            FindMemoryValue("m", Convert.ToInt32(memorykey, 16));


        }

        public static bool InputMatches(string input, string pattern)
        {
            try
            {


                int index = 1;
                //input = "铁中棠(moonyj)告诉你 : 收我";
                //pattern = @"\b(\w+)\((.*?)\)告诉你 : 收我";
                //pattern = @"\【moonpri旅行团\】铁中棠\(moonpri\) : kill\s+(\w+)";
                Boolean first = true;

                MatchCollection matches = Regex.Matches(input, pattern);

                if (matches.Count > 0)
                {
                    mathvalue = new Dictionary<int, string>();
                }

                foreach (Match match in matches)
                {
                    foreach (Group group in match.Groups)
                    {
                        if (!first)
                        {
                            Boolean find = false;
                            foreach (var item in mathvalue)
                            {
                                if (item.Key == index)
                                {
                                    find = true;
                                    break;
                                }
                            }
                            if (find)
                            {
                                mathvalue[index] = group.Value;

                            }
                            if (!find)
                            {
                                mathvalue.Add(index, group.Value);
                                index++;
                            }
                        }
                        if (first)
                        {
                            first = false;
                        }

                    }
                }

                if (matches.Count > 0)
                {
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return false;
        }



        /// <summary>
        /// 通配命令替换
        /// </summary>
        /// <param name="pattern"></param>
        /// <returns></returns>
        static string inputpatternreplace(string pattern)
        {
            //string cn = @"([\u4e00-\u9fa5])"; // 匹配汉字
            string cn = "*";
            int findpos = pattern.IndexOf("%*");
            if (findpos >= 0)
            {
                pattern = @pattern.Replace("%*", cn);
            }
            string en = @"[a-zA-Z]";
            findpos = pattern.IndexOf("%e");
            if (findpos >= 0)
            {
                pattern = pattern.Replace("%e", en);
            }
            string space = @"\s+"; //至少一个空格
            findpos = pattern.IndexOf("%s");
            if (findpos >= 0)
            {
                pattern = pattern.Replace("%s", space);
            }
            //匹配括号
            string kh = @"\("; //左括号
            findpos = pattern.IndexOf("(");
            if (findpos >= 0)
            {
                pattern = pattern.Replace("(", kh);
            }
            kh = @"\)"; //右括号
            findpos = pattern.IndexOf(")");
            if (findpos >= 0)
            {
                pattern = pattern.Replace(")", kh);
            }

            return pattern;
        }


        public static string GetPtrToIpAddr(IntPtr hWnd, string address)
        {
            byte[] bt = new byte[1024];
            int calcID;
            int dataAddress;
            string datastr;
            int readByte;
            //由窗体句柄获得进程ID
            GetWindowThreadProcessId(hWnd, out calcID);
            //由进程ID获得进程句柄
            int hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE, false, calcID);
            //读取进程指定的内存地址
            byte[] lpBuffer = new byte[255];
            ReadProcessMemory(hProcess, Convert.ToInt32(address, 16), lpBuffer, 255, out readByte);
            string str = System.Text.Encoding.UTF8.GetString(lpBuffer);
            return str;
        }

        private static int CheckNetStatus(IntPtr hWnd)
        {
            if (!"Y".Equals(reconnetFlag))
            {
                return 0;
            }
            string serverAddress = "203.70.8.215";
            ushort serverPort = 4321;
            string netstatus = string.Empty;
            int calcID;
            GetWindowThreadProcessId(hWnd, out calcID);

            bool found = false;
            foreach (var tcp in NetProcessAPI.GetAllTcpConnections(calcID, serverAddress, serverPort))
            {
                if (tcp.owningPid == calcID)
                {
                    found = true;
                    netstatus = tcp.state.ToString();
                    //netstatus = calcID + " -> " + tcp.RemoteAddress + ":" + tcp.RemotePort + " -> " + Enum.GetName(typeof(NetProcessAPI.ConnectionState), tcp.state);
                    break;
                }
            }
            if (!found)
            {
                netstatus = "Closed";
                //netstatus = calcID + " -> " + serverAddress + ":" + serverPort + " -> " + Enum.GetName(typeof(NetProcessAPI.ConnectionState), NetProcessAPI.ConnectionState.Closed);
            }

            if (netstatus != "Established")
            {
                return -1;
            }

            return 0;
        }

        private static Boolean checkifresult(string tmpstr)
        {
            Boolean ifResult = false;
            int checkvalue = 0;
            //获取if的变量 if (%m > 200)
            string ifvar = string.Empty;
            ifvar = tmpstr.Substring(5, 1);
            string ifSymbol = tmpstr.Substring(7, 1);
            int ifvalue = Convert.ToInt32(tmpstr.Substring(9, tmpstr.Length - 10));
            string memorykey = string.Empty;

            switch (ifvar)
            {
                case "x": //x 坐标
                    memorykey = Properties.Settings.Default.Memory_x;
                    break; 
                case "y": //y 坐标
                    memorykey = Properties.Settings.Default.Memory_y;
                    break;
                case "h": // 当前生命
                    memorykey = Properties.Settings.Default.Memory_h;
                    break;
                case "m": // 当前魔法
                    memorykey = Properties.Settings.Default.Memory_m;
                    break;
                default:
                    break;
            }

            if (!string.IsNullOrEmpty(memorykey))
            {
                FindMemoryValue(ifvar, Convert.ToInt32(memorykey, 16));
            }

            checkvalue = gamevalue[ifvar];

            switch (ifSymbol)
            {
                case "="://等于
                    if (checkvalue == ifvalue)
                    {
                        ifResult = true;
                    }
                    break;
                case ">"://大于
                    if (checkvalue > ifvalue)
                    {
                        ifResult = true;
                    }
                    break;
                case "<"://小于
                    if (checkvalue < ifvalue)
                    {
                        ifResult = true;
                    }
                    break;
                case "~"://不等于
                    if (ifvalue != checkvalue)
                    {
                        ifResult = true;
                    }
                    break;
                default:
                    ifResult = false;
                    break;
            }
            return ifResult;
        }

        #region 调用系统keyboard dll

        private static int Callkeyboard(string commandtmp, double delaytime)
        {
            if (commandtmp.Length > 9)
            {
                if (commandtmp.Substring(0, 9) == "@&KeyDown")
                {
                    string str = string.Empty;
                    int flag = 0;


                    int start = commandtmp.IndexOf(" ", 0);
                    int end = commandtmp.IndexOf(",", 0);
                    str = commandtmp.Substring(start + 1, end - start - 1);
                    flag = Convert.ToInt32(commandtmp.Substring(end + 1));

                    ScriptRun.KeydownPost(programhWnd, str);

                    truedelay(delaytime);
                    return 1;
                }
            }
            return 0;
        }

        #endregion

        #region 调用大漠寻图
        private static void Get()
        {
            object intX, intY = 0;
            prdm.FindPic(0, 0, 1377, 768, "2.bmp", "203040", 0.3, 0, out intX, out intY);
            Log.WriteLog("x", intX.ToString(), "循环记录");
            Log.WriteLog("y", intY.ToString(), "循环记录");
        }

        private static void getpoint()
        {
            object intX, intY = 0;
            prdm.GetCursorPos(out intX, out intY);
            Log.WriteLog("x当前坐标", intX.ToString(), "循环记录");
            Log.WriteLog("y当前坐标", intY.ToString(), "循环记录");
        }

        #endregion

    }
}
